import Toast from '@vant/weapp/toast/toast';
// 导入发音接口即“InnerAudioContext”API
const innerAudioContext = wx.createInnerAudioContext();
// 声明录音管理器模块
const recorderManager = wx.getRecorderManager()
let toast;
Page({
  data:{
    showPopUp: false,//是否展示弹出层
    userInfo: {},// 因为是第一个页面，所以要获取用户相关信息
    //是否已经获取用户信息
    hasUserInfo: false,
    //是否可以调用获取信息得函数
    canIUseGetUserProfile: false,
    navArr: ['识词汇','学典故','查词库'], // 导航栏
    nowList: 0,// 0代表认识列表 1代表陌生列表
    nowStory: {}, //  当前正在展示的典故
    questionList: [], // 问题列表
    nowQuestion: {}, // 当前问题
    nowSelect: -1, // 在选择时当前选择了哪个
    questionNextIdx: 0,// 下一个题目下标
    questionNowIdx: 0,// 当前正在做的题目的下标
    nowWord: {},// 当前正在背的单词
    showDefinition: false,//是否显示中文解释
    wordList: [], // 当前正在展示的全部单词
    knowWordList: [],// 所有知道的单词
    blurWordList: [],// 所有模糊的单词
    startAnswer: false,// 是否开始答题
    isTranslate: false,// 典故是否显示中文释义
    showNowWord: true,// 是否显示当前单词
    showAllStory: false,// 弹出框展示所有典故
    storyList: [],

    // 发音，音频数据
    audiosrc: 'http://dict.youdao.com/dictvoice?type=1&audio=play',
    audioDuration: 0,
  },
  // 弹出层关闭
  onClose() {
    this.setData({ show: false });
  },
  onLoad: function() {
    const self = this;
    this.setData({
      canIUseGetUserProfile : true
    })
    //获取用户的本地缓存数据，userinfo信息是在用户授权登录时保存的
    var info = wx.getStorageSync("userinfo");
    console.log(info)
    //当本地缓存的用户名称不为""或者null时，设置userinfo信息
    if(info.nickName != '' && info.nickName != null){
       this.setData({
           userInfo: info,
           hasUserInfo:true,
           canIUseGetUserProfile:true
       })
     }
    if (!this.data.hasUserInfo && this.data.canIUseGetUserProfile) {
      this.setData({
        showPopUp:true
      })
    }
    // 清空缓存信息，测试使用  
    // wx.removeStorage({
    //     key: 'userinfo',
    // });

    wx.request({
      // url: 'http://localhost:8080/word/getStory?id=-1',
      url: 'http://47.120.31.85:8080/word/getStory?id=-1',
      method: 'GET',
      success: function(res) {
        self.setData({
          nowStory: res.data.data[0],
          storyList: res.data.data,
        })
      }
    })
    // 获取全部问题
    wx.request({
      url: 'http://47.120.31.85:8080/word/getAllQuestion',
      // url: 'http://localhost:8080/word/getAllQuestion',
      method: 'GET',
      success: function(res) {
        self.setData({
          questionList: res.data.data,
          nowQuestion: res.data.data[0]
        })
      }
    })
    // 获取用户认识的单词
    wx.request({
      // url: 'http://localhost:8080/word/getAllKnowWord?username=' + self.data.userInfo.nickName,
      url: 'http://47.120.31.85:8080/word/getAllKnowWord?username=' + self.data.userInfo.nickName,
      method: 'GET',
      success: function(res) {
        self.setData({
          wordList: res.data.data,
          knowWordList: res.data.data
        })
      }
    })
    // 获取用户模糊的单词
    wx.request({
      // url: 'http://localhost:8080/word/getAllBlurWord?username=' + self.data.userInfo.nickName,
      url: 'http://47.120.31.85:8080/word/getAllBlurWord?username=' + self.data.userInfo.nickName,
      method: 'GET',
      success: function(res) {
        self.setData({
          blurWordList: res.data.data
        })
      }
    })
    self.getRandomWord()
    // 发音API初始化
    this.Initialization();
  },
  onShow: function () {
    if (typeof this.getTabBar === 'function' &&  this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0     //这里的数字设置当前页面在tabbar里对应的序列，从0开始
      })
    }
  },
  //第一次获取用户信息
  getUserProfile : function(e){
    wx.getUserProfile({
      desc: '我们需要获取您的微信个人信息',
      success:(res)=>{
          let username = res.userInfo.nickName
          let avatarUrl = res.userInfo.avatarUrl
          this.setData({
            userinfo:res.userInfo,
          })
          wx.setStorageSync('userinfo', res.userInfo)
          console.log(res.userInfo)
          const userFormData = {
            username: username,
            avatarUrl: avatarUrl
          }
          // 能获取用户信息 说明第一次调用 存到数据库中 
          wx.request({
            // url: 'http://localhost:8080/word/insertUser',
            url: 'http://47.120.31.85:8080/word/insertUser',
            data: userFormData,
            method: 'POST',
            success: function(res) {
              console.log('用户插入成功')
            }
          })
          this.setData({
            showPopUp:false
          })
      },
      fail:function(e){
          wx.showToast({
            title: '你选择了取消',
            icon: "none",
            duration: 1500,
            mask: true
          })
      }
    })
  },
  changeStory(data) {
    const self = this;
    let id = data.currentTarget.dataset.item
    wx.request({
      // url: 'http://localhost:8080/word/getStory?id=-1',
      url: 'http://47.120.31.85:8080/word/getStory?id=' + id,
      method: 'GET',
      success: function(res) {
        self.setData({
          nowStory: res.data.data,
        })
      }
    })
  },
  onReady() {
    toast = this.selectComponent("#toast")
  },
  seeKnowWord() {
    const self = this;
    this.setData({
      wordList: self.data.knowWordList
    })
  },
  seeBlurWord() {
    const self = this;
    this.setData({
      wordList: self.data.blurWordList
    })
  },
  chooseStory() {
    this.setData({
      showAllStory:true
    })
  },

  onClose() {
    this.setData({ showAllStory: false });
  },
  getRandomWord() {
    const self = this;
    wx.request({
      // url: 'http://localhost:8080/word/getRandomWord',
      url: 'http://47.120.31.85:8080/word/getRandomWord',
      method: 'GET',
      success: function(res) {
        self.setData({
          nowWord: res.data.data
        })
      }
    })
    self.setData({
      showDefinition: false,
      audiosrc: 'http://dict.youdao.com/dictvoice?type=1&audio=' + self.data.nowWord.word,
    })
    self.Initialization();
  },
  changeNav(data) {
    let index = data.currentTarget.dataset.item
    if ( index == 1 ) return;
    const self = this;
    let first = self.data.navArr[0]
    let second = self.data.navArr[1]
    let third = self.data.navArr[2]
    if ( index == 0 ) {
      self.setData({
        navArr:[third,first,second]
      })
    }
    if ( index == 2 ) {
      self.setData({
        navArr:[second,third,first]
      })
    }
  },
  translateToChinese() {
    const self = this;
    this.setData({
      isTranslate: !self.data.isTranslate
    })
  },
  selectOption(data) {
    let index = data.currentTarget.dataset.item
    this.setData({
      nowSelect: index
    })
  },
  nextQuestion() {
    const self = this;
    if (this.data.questionNextIdx == this.data.questionNowIdx) {
      Toast.fail('请先完成本题');
    }else {
      this.setData({
        questionNowIdx: self.data.questionNextIdx,
        nowQuestion: self.data.questionList[self.data.questionNextIdx] 
      })
    }
  },
  backToStory() {
    const self = this;
    this.setData({
      startAnswer: !self.data.startAnswer
    })
  },
  submitQuestion() {
    const self = this;
    if ( this.data.nowSelect == this.data.nowQuestion.trueOption ) {
      Toast.success('回答正确');
      this.setData({
        questionNextIdx: self.data.questionNextIdx + 1,
        nowSelect: -1
      })
      
    }else {
      Toast.fail('回答错误，再试试吧！');
    }
  },
  startTest() {
    const self = this;
    this.setData({
      startAnswer: !self.data.startAnswer
    })
  },
  // 蒙词拼写方法
  showInput() {
    const _this = this;
    _this.setData({
      showNowWord: false
    })
    wx.showModal({
      editable:true,//显示输入框
      placeholderText:`音标提示：[${_this.data.nowWord.pron}]`,//显示输入框提示信息
      success: res => {
        if (res.confirm) { //点击了确认
          if (res.content == _this.data.nowWord.word) {
            wx.showToast({
              title: '拼写正确',
              icon: 'success',
              duration: 2000//持续的时间
            })
          }else {
            wx.showToast({
              title: '拼写错误',
              icon: 'error',
              duration: 2000//持续的时间
            })
          }
        } else {
          console.log('用户点击了取消')
        }
        _this.setData({
          showNowWord: '1'
        })
      }
    })
  },

  //点击模糊后执行的函数
  blur: function () {
    const self = this;
    const formData = {
      word: self.data.nowWord.word,
      definition: self.data.nowWord.definition
    }
    const learnHistoryFormData = {
      word: self.data.nowWord.word,
      type: self.data.nowWord.type,
      username: self.data.userInfo.nickName
    }
    wx.request({
      url: 'http://47.120.31.85:8080/word/blur?username=' + self.data.userInfo.nickName,
      // url: 'http://localhost:8080/word/blur?username=' + self.data.userInfo.nickName,
      data: formData,
      method: 'POST',
      success: function(res) {
        console.log('认识Request发送成功')
      }
    })
    wx.request({
      url: 'http://47.120.31.85:8080/word/addLearnHistory',
      // url: 'http://localhost:8080/word/addLearnHistory',
      data: learnHistoryFormData,
      method: 'POST',
      success: function(res) {
        console.log('学习记录添加成功')
      }
    })
    self.getRandomWord()
  },

  // 点击认识执行的函数
  know: function (e) {
    const self = this;
    const formData = {
      word: self.data.nowWord.word,
      definition: self.data.nowWord.definition
    }
    const learnHistoryFormData = {
      word: self.data.nowWord.word,
      type: self.data.nowWord.type,
      username: self.data.userInfo.nickName
    }
    wx.request({
      url: 'http://47.120.31.85:8080/word/know?username=' + self.data.userInfo.nickName,
      data: formData,
      method: 'POST',
      success: function(res) {
        console.log('认识Request发送成功')
      }
    })
    wx.request({
      url: 'http://47.120.31.85:8080/word/addLearnHistory',
      data: learnHistoryFormData,
      method: 'POST',
      success: function(res) {
        console.log('学习记录添加成功')
      }
    })
    self.getRandomWord()
  },

  // 显示单词中文
  showDefinition() {
    this.setData({
      showDefinition: true,
    })
  },
  //初始化播放器，获取duration
  Initialization() {
    var t = this;
    //设置src
    innerAudioContext.src = this.data.audiosrc;
    //运行一次
    innerAudioContext.onCanplay(() => {
      //初始化duration
      innerAudioContext.duration
      setTimeout(function () {
        //延时获取音频真正的duration
        var duration = innerAudioContext.duration;
        var min = parseInt(duration / 60);
        var sec = parseInt(duration % 60);
        if (min.toString().length == 1) {
          min = `0${min}`;
        }
        if (sec.toString().length == 1) {
          sec = `0${sec}`;
        }
        t.setData({
          audioDuration: innerAudioContext.duration,
          showTime2: `${min}:${sec}`
        });
      }, 1000)
    })
  },
  //播放按钮
  playAudio() {
    innerAudioContext.play();
  },

  // 录音
  beginRecord:function(e) {
    // 监听录音开始事件
    recorderManager.onStart(() => {
    console.log('recorder start')
    })
    // 监听已录制完指定帧大小的文件事件。如果设置了 frameSize，则会回调此事件。
    recorderManager.onFrameRecorded((res) => {
    const { frameBuffer } = res
    console.log('frameBuffer.byteLength', frameBuffer.byteLength)
    })
    //录音的参数
    const options = {
      duration: 10000,//指定录音的时长，单位 ms
      sampleRate: 16000,//采样率
      numberOfChannels: 1,//录音通道数
      encodeBitRate: 96000,//编码码率
      format: 'mp3',//音频格式，有效值 aac/mp3
      frameSize: 50,//指定帧大小，单位 KB
    }
    //开始录音
    recorderManager.start(options);
  },

  // 停止录音并上传数据
 endRecord:function(e) {
    const self = this;
    self.setData({
      message: '识别中',
      showScore: false
    })
    self.showToast()
    //停止录音
    recorderManager.stop();
    //监听录音停止事件，执行上传录音文件函数
    recorderManager.onStop((res) => {
      console.log('recorder stop', res)
      //返回值res.tempFilePath是录音文件的临时路径 (本地路径)
      self.setData({
        tempFilePath: res.tempFilePath
      })
      innerAudioContext.src = res.tempFilePath
      //上传录音文件
      var uploadTask = wx.uploadFile({
      //没有method，自动为POST请求
      filePath: res.tempFilePath,
      name: 'recordFile',  //这个随便填
      url: 'http://47.120.31.85:8080/word/speechAssessment?text=' + self.nowWord.content, //填写自己服务器的地址。
      header: {
      "Content-Type": "multipart/form-data" //必须是这个格式
      },
      success:(e) => {
        var jsonObj = JSON.parse(e.data);
        var data = jsonObj["data"]
        let totalScore = data["totalScore"]
        let isReject = data["isRejected"]
        let message = ''
        if ( isReject ) {
          message = '识别失败，请再大声朗读。'
        }else {
          message = '识别成功。'
        }
        self.setData({
          audioMessage: message,
          totalScore: totalScore,
          showScore: true,
        })
        self.showToast()
      },
      fail: (e) => {
        let message = '识别失败'
        let totalScore = 0
        self.setData({
          audioMessage: message,
          totalScore: totalScore,
          showScore: true,
        })
        self.showToast()
      }
      });
      uploadTask.onProgressUpdate((e) => {
      console.log(e);
      console.log('期望上传的总字节数：' + e.totalBytesExpectedToSend);
      console.log('已经上传的字节数' + e.totalBytesSent);
      })
    })
  },

  changeStatus(data) {
    let item = data.currentTarget.dataset.item;
    const self = this;
    const formData = {
      word: item.word
    }
    if ( item.blur == 0 ) {
      wx.request({
        url: 'http://47.120.31.85:8080/word/blur?username=' + self.data.userInfo.nickName,
        data: formData,
        method: 'POST',
        success: function(res) {
          console.log('单词状态修改成功')
        }
      })
    }else {
      wx.request({
        url: 'http://47.120.31.85:8080/word/know?username=' + self.data.userInfo.nickName,
        data: formData,
        method: 'POST',
        success: function(res) {
          console.log('单词状态修改成功')
        }
      })
    }
  },

  showToast(e) {
    let options = {}
     toast && toast.show(options)
  },
})